package com.hulizuofang.wol.chat.server;

import java.util.HashSet;
import java.util.Set;

import org.nicocube.appengine.util.dao.Dao;
import org.nicocube.appengine.util.dao.DaoException;
import org.nicocube.appengine.util.dao.DaoQuery;
import org.nicocube.appengine.util.dao.DaoRequest;
import org.nicocube.appengine.util.dao.DaoResultContainer;
import org.nicocube.appengine.util.dao.NoResultFoundException;
import org.nicocube.appengine.util.dao.PersistenceAccessor;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.hulizuofang.wol.chat.client.ui.user.ChatUser;

@Singleton
public class ChatUserRepository {

	private final Dao dao;

	@Inject
	public ChatUserRepository(Dao dao) {
		this.dao = dao;
	}
	
	public ChatUser login(final String login) {
		final DaoResultContainer<ChatUser> result = new DaoResultContainer<ChatUser>();
		dao.eval(new DaoRequest() {
			@Override
			public void playOn(PersistenceAccessor pa) throws DaoException {
				DaoQuery<ChatUser> query = pa.newQuery(ChatUser.class);
				query.addCriteria("login", String.class, login);
				try {
					result.set(query.execute());					
				} catch (NoResultFoundException e) {
					result.set(pa.makePersistent(new ChatUser(login)));
				}
			}
		});
		return result.get();
	}

	public Set<ChatUser> getOnlineUsers() {
		final Set<ChatUser> result = new HashSet<ChatUser>();
		dao.eval(new DaoRequest() {
			@Override
			public void playOn(PersistenceAccessor pa) throws DaoException {
				DaoQuery<ChatUser> query = pa.newQuery(ChatUser.class);
				query.addCriteria("active", boolean.class, true);
				result.addAll(query.executeList());					
			}
		});
		return result;
	}


}
